<?php

require_once 'classes/resources/IResource.php';
require_once 'classes/vo/Topic.php';
require_once 'classes/service/ServiceLocator.php';

class TopicsResource implements IResource {
	
	
	public function processGet($requestParts) {
		Log::instance()->debug("processGet()");
		
		$jsonTopics = array();
		$topics = ServiceLocator::getTopicsService()->fetchAllTopics();
		foreach ($topics as $topic) {
			$jsonTopics[] = array(
				'id' => $topic->id,
				'title' => $topic->title
			);
		}
		
		$json = array(
			'Response' => array(
				'Head' => array(
					'Version' => '0.1'
				),
				'Body' => array(
					'Topics' => $jsonTopics
				)
			)
		);
		
		Log::instance()->debug("encoding object to json.");
		$jsonString = json_encode($json);
		Log::instance()->debug("writing: " . $jsonString);
		echo 'var result = ' . $jsonString . ';';
		
		if(count($requestParts) == 2 && is_numeric($requestParts[1])) {
			// TODO implement new feature - ServiceLocator::getTopicsService()->fetchTopicsDetail();
			Log::instance()->warn("not yet implemented feature!");
			
		} else {
			
			/*
			$result =
				'{ "Response" : {' .
					' "Head": {' .
					' },' .
					' "Body": {' .
					' }' . 
				' } } ';*/
		}
	}
	
	private function requestAllTopics() {
		echo '{ "result" : { ' .
				' "version": "0.1", '.
				' "data": [ '.
					' { "id": "1", "title": "PHP" }, ' .
					' { "id": "2", "title": "GWT" } ' .
				' ]' .
			' } } ';
		
		/*
		echo '{ [ '.
			' { "id": "1", "title": "PHP" }, ' .
			' { "id": "1", "title": "GWT" } ' .
			' ] }';
		*/
	}
	
	public function processPut($requestParts) {
		Log::instance()->debug("processPut()");
		
	}
	public function processPost($requestParts) {
		Log::instance()->debug("processPost()");
		
		$jsonString = file_get_contents('php://input');
		$topic = Topic::newByJson($jsonString);
		
		Log::instance()->debug("Adding topic: " . $topic);
		
	}
	public function processDelete($requestParts) {
		Log::instance()->debug("processDelete()");
		
	}
}

?>